package cn.ym.ymcc.service.impl;

import cn.ym.ymcc.constant.CustomConstant;
import cn.ym.ymcc.domain.Course;
import cn.ym.ymcc.domain.CourseMarket;
import cn.ym.ymcc.domain.CourseOrder;
import cn.ym.ymcc.domain.CourseOrderItem;
import cn.ym.ymcc.dto.CourseDto;
import cn.ym.ymcc.dto.CourseInfoDto;
import cn.ym.ymcc.dto.CourseOrderDto;
import cn.ym.ymcc.feign.CourseServerFeign;
import cn.ym.ymcc.mapper.CourseOrderMapper;
import cn.ym.ymcc.result.JSONResult;
import cn.ym.ymcc.service.ICourseOrderItemService;
import cn.ym.ymcc.service.ICourseOrderService;
import cn.ym.ymcc.utils.AssertUtil;
import cn.ym.ymcc.utils.CodeGenerateUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 210513347@qq.com
 * @since 2023-05-19
 */
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {


    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Autowired
    private CourseServerFeign courseServerFeign;


    /**
     * 保存订单和订单详情
     * @param courseOrderDto
     */
    @Override
    public String placeOrder(CourseOrderDto courseOrderDto) {
        /**
         * 1.参数校验
         * 2.token校验
         * 3.保存订单
         * 4.保存订单明细
         * 5.删除redis中的token
         * @param courseOrderDto
         */
        //1.搞一个用户的id
        Long uid=3L;//todo
        //2.获取前端传过来的课程id
        List<Long> courseIds = courseOrderDto.getCourseIds();
        //3.把课程id集合转为字符串
        String courseId = courseIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        //4.拼接redis的key
        String redisKey = String.format(CustomConstant.REDIS_TOKEN_KEY,uid,courseId);

        //5.取出redis中存储的token
        String redisToken = (String) redisTemplate.opsForValue().get(redisKey);

        //6.判断前端传过来的token和redis中的token是否一致
        AssertUtil.isEquals(courseOrderDto.getToken(), redisToken, "请不要重复提交");
        //7.创建课程订单
        CourseOrder courseOrder = new CourseOrder();
        courseOrder.setCreateTime(new Date());//设置创建时间
        courseOrder.setOrderNo(CodeGenerateUtils.generateOrderSn(uid)); //设置订单号
        courseOrder.setTotalCount(courseIds.size()); //课程数量
        courseOrder.setStatusOrder(CourseOrder.WAIT_PAY);//待支付
        courseOrder.setUserId(uid);//保存哪个用户购买的
        //8.根据课程id查询课程详情
        JSONResult infoJSONResult = courseServerFeign.info(courseId);
        AssertUtil.isTrue(infoJSONResult.isSuccess(), infoJSONResult.getMessage());
        //9.把json字符串转为课程详情dto
        CourseInfoDto courseInfoDto = JSONObject.parseObject(JSONObject.toJSONString(infoJSONResult.getData()), CourseInfoDto.class);
        //设置订单总金额
        courseOrder.setTotalAmount(courseInfoDto.getTotalAmount());
        courseOrder.setPayAmount(courseOrder.getTotalAmount());
        courseOrder.setDiscountAmount(new BigDecimal("0"));
        courseOrder.setPayType(courseOrderDto.getPayType());
        courseOrder.setOrderType(courseOrderDto.getType());
        List<CourseDto> courseInfos = courseInfoDto.getCourseInfos();
        String title = "购买课程 [%s] , 支付[%s]元";
        //获取课程名
        String courseNames = courseInfos.stream()
                .map(CourseDto::getCourse)//只要course对象
                .map(Course::getName)//只要课程对象的name
                .collect(Collectors.joining(",")); //把多个name以字符串逗号进行拼接
        //设置占位符的值
        title = String.format(title, courseNames, courseOrder.getTotalAmount());
        //设置课程订单标题
        courseOrder.setTitle(title);
        //保存订单
        super.insert(courseOrder);
        //创建集合，来封装订单下面所有的课程订单明细，方便做批量保存
        List<CourseOrderItem> items = new ArrayList<>();
        //保存订单明细
        courseInfos.forEach(c->{
            //获取course
            Course course = c.getCourse();
            //获取课程营销对象
            CourseMarket courseMarket = c.getCourseMarket();

            //创建课程订单明细
            CourseOrderItem item = new CourseOrderItem();
            item.setOrderId(courseOrder.getId());
            item.setAmount(courseMarket.getPrice());
            //课程数量
            item.setCount(1);
            //求小计
            item.setSubtotalAmount(item.getAmount().multiply(BigDecimal.valueOf(item.getCount())));
            //设置创建时间
            item.setCreateTime(new Date());
            item.setCourseId(course.getId());
            item.setCourseName(course.getName());
            item.setCoursePic(course.getPic());
            item.setVersion(0);
            item.setOrderNo(courseOrder.getOrderNo());
            //添加课程订单明细
            items.add(item);
        });
        //批量保存课程订单明细
        courseOrderItemService.insertBatch(items);
        //删除redis中的token
        redisTemplate.delete(redisKey);



        return null;
    }




























}
